package cn.heycm.blog.common.mybatis;

import cn.heycm.blog.common.entity.page.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.util.CollectionUtils;

import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * 分页工具
 *
 * @author hey
 * @version 1.0
 * @since 2024/9/19 11:17
 */
public class PageUtil {

    private PageUtil() {}

    public static <E> Page<E> convert(PageInfo<E> pageInfo) {
        Page<E> page = new Page<>();
        page.setPage(pageInfo.getPageNum());
        page.setSize(pageInfo.getPageSize());
        page.setTotal(pageInfo.getTotal());
        page.setPages(pageInfo.getPages());
        page.setList(pageInfo.getList());
        return page;
    }

    public static <E> Page<E> convert(Supplier<PageInfo<E>> supplier) {
        return PageUtil.convert(supplier.get());
    }

    public static <T, U> Page<U> convert(Page<T> page, Function<T, U> function) {
        Page<U> convert = new Page<>();
        convert.setPage(page.getPage());
        convert.setSize(page.getSize());
        convert.setTotal(page.getTotal());
        convert.setPages(page.getPages());
        if (CollectionUtils.isEmpty(page.getList())) {
            return convert;
        }
        convert.setList(page.getList().stream().map(function).collect(Collectors.toList()));
        return convert;
    }

    public static <T, U> Page<U> convert(PageInfo<T> pageInfo, Function<T, U> function) {
        Page<U> convert = new Page<>();
        convert.setPage(pageInfo.getPageNum());
        convert.setSize(pageInfo.getSize());
        convert.setTotal(pageInfo.getTotal());
        convert.setPages(pageInfo.getPages());
        if (CollectionUtils.isEmpty(pageInfo.getList())) {
            return convert;
        }
        convert.setList(pageInfo.getList().stream().map(function).collect(Collectors.toList()));
        return convert;
    }
}
